using System.Collections.Generic;
using ProtoModels;
using UnityEngine;

public class PractiseLayer : MonoBehaviour
{
	public TrainingButton buttonPrefab;

	public UIGrid grid;

	public UIScrollView view;

	private List<TrainingButton> trainingButtons = new List<TrainingButton>();

	private bool isAligned;

	public List<PlayerStatsManager.SkillType> skillsToDisplay = new List<PlayerStatsManager.SkillType>();

	private List<TrainingConfig.Training> _myTrainings;

	private List<TrainingConfig.Training> myTrainings
	{
		get
		{
			if (_myTrainings == null)
			{
				_myTrainings = GetMyTrainingList();
			}
			return _myTrainings;
		}
	}

	private void OnEnable()
	{
		GeneratePage();
		isAligned = false;
	}

	private List<TrainingConfig.Training> GetMyTrainingList()
	{
		List<TrainingConfig.Training> list = new List<TrainingConfig.Training>();
		foreach (TrainingConfig.Training skillTraining in TrainingConfig.instance.skillTrainings)
		{
			foreach (TrainingConfig.StatUpdateInfo item in skillTraining.statUpdateInfo)
			{
				if (item.trainingType == TrainingType.Skill && IsAttrTypeInDisplayList(item.skillType))
				{
					list.Add(skillTraining);
					break;
				}
			}
		}
		return list;
	}

	private bool IsAttrTypeInDisplayList(PlayerStatsManager.SkillType type)
	{
		foreach (PlayerStatsManager.SkillType item in skillsToDisplay)
		{
			if (item == type)
			{
				return true;
			}
		}
		return false;
	}

	private void GeneratePage()
	{
		InitialiseButtonsForPage();
	}

	private void InitialiseButtonsForPage()
	{
		for (int i = 0; i < myTrainings.Count; i++)
		{
			if (i >= trainingButtons.Count)
			{
				TrainingButton component = NGUITools.AddChild(grid.gameObject, buttonPrefab.gameObject).GetComponent<TrainingButton>();
				component.gameObject.name = GGFormat.IndexName(i);
				trainingButtons.Add(component);
			}
			InitialiseButton(trainingButtons[i], myTrainings[i]);
		}
		for (int j = myTrainings.Count; j < trainingButtons.Count; j++)
		{
			InitialiseButton(trainingButtons[j], null);
		}
		grid.Reposition();
		isAligned = false;
	}

	private void InitialiseButton(TrainingButton button, TrainingConfig.Training training)
	{
		button.gameObject.SetActive(training != null);
		if (training != null)
		{
			button.Init(training, skillsToDisplay[0]);
		}
	}

	private void Update()
	{
		if (!isAligned && trainingButtons.Count > 0)
		{
			UITools.AlignToLeftOnScroll(trainingButtons[0].gameObject.GetComponent<UIWidget>(), view, 40f);
			isAligned = true;
		}
	}
}
